
package com.spring.demo.app.web.controller;

import com.spring.demo.app.base.BaseConstants;
import com.spring.demo.app.web.response.WebResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;


/**
 * <p>异常处理类handlerController</p>
 * @author YANGHENG940 2017年2月15日 下午7:18:38
 * @version V1.0   
 */
@RestController
@ControllerAdvice
public class ExceptionHandlerController {

  private static Logger logger = LoggerFactory.getLogger(ExceptionHandlerController.class);
  
  @ExceptionHandler(Exception.class)
  public WebResponse exceptionHandler(Exception e) {
    WebResponse br = new WebResponse();
    logger.error(ExceptionHandlerController.class.getSimpleName(), e);
    br.setResultCode(BaseConstants.WEB_ERROR_CODE);
    br.setResultMessage(BaseConstants.WEB_ERROR_MSG + "[" + e.getMessage() + "]");
    return br;
  }


  @ExceptionHandler(DuplicateKeyException.class)
  public WebResponse duplicateKeyExceptionHandler(Exception e) {
    WebResponse br = new WebResponse();
    logger.error(ExceptionHandlerController.class.getSimpleName(), e);
    br.setResultCode(BaseConstants.WEB_ERROR_CODE);
    br.setResultMessage(BaseConstants.WEB_ERROR_MSG + "[不允许出现重复数据，请检查]");
    return br;
  }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public WebResponse dataIntegrityViolationExceptionExceptionHandler(Exception e) {
        WebResponse br = new WebResponse();
        logger.error(ExceptionHandlerController.class.getSimpleName(), e);
        br.setResultCode(BaseConstants.WEB_ERROR_CODE);
        br.setResultMessage(BaseConstants.WEB_ERROR_MSG + "[数据类型或长度出现异常]");
        return br;
    }

}
